<template>
  <div class="outbound-detail-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>出库单详情 - {{ outboundInfo.outboundCode || outboundCode }}</h2>
          <div class="header-buttons">
            <el-button @click="refreshData" :loading="loading" type="primary" plain>刷新</el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <!-- 基础信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <h3>基础信息</h3>
        </template>
        <el-row :gutter="20" v-loading="loading">
          <el-col :span="8">
            <div class="info-item">
              <label>出库单号：</label>
              <span>{{ outboundInfo.outboundCode }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>出库类型：</label>
              <span>{{ outboundInfo.inOutTypeName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>仓库名称：</label>
              <span>{{ outboundInfo.warehouseName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>出库日期：</label>
              <span>{{ formatDate(outboundInfo.outboundDate) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>联系人：</label>
              <span>{{ outboundInfo.contact }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>收货人：</label>
              <span>{{ outboundInfo.consignee }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>联系方式：</label>
              <span>{{ outboundInfo.contactPhone }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>操作员：</label>
              <span>{{ outboundInfo.userName }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>状态：</label>
              <el-tag :type="getStatusType(outboundInfo.status)">{{ getStatusText(outboundInfo.status) }}</el-tag>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>总数量：</label>
              <span>{{ outboundInfo.outboundAllNum }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>总金额：</label>
              <span>¥{{ (outboundInfo.outboundAllMoney || 0).toFixed(2) }}</span>
            </div>
          </el-col>
          <el-col :span="8">
            <div class="info-item">
              <label>创建人：</label>
              <span>{{ outboundInfo.creator }}</span>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="info-item">
              <label>备注：</label>
              <span>{{ outboundInfo.remark || '无' }}</span>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="info-item">
              <label>创建日期：</label>
              <span>{{ formatDateTime(outboundInfo.createDate) }}</span>
            </div>
          </el-col>
        </el-row>
      </el-card>

      <!-- 出库明细 -->
      <el-card class="detail-card" shadow="never">
        <template #header>
          <h3>出库明细</h3>
        </template>
        <el-table :data="outboundDetails" border stripe style="width: 100%" v-loading="detailLoading">
          <el-table-column type="index" width="50" label="序号"></el-table-column>
          <el-table-column prop="goodsCode" label="货品编号" width="120"></el-table-column>
          <el-table-column prop="goodsName" label="货品名称" min-width="150"></el-table-column>
          <el-table-column prop="specModel" label="规格型号" width="120"></el-table-column>
          <el-table-column prop="unitPrice" label="单价" width="100">
            <template #default="scope">
              ¥{{ (scope.row.unitPrice || 0).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="outboundNum" label="出库数量" width="100"></el-table-column>
          <el-table-column prop="outboundMoney" label="出库金额" width="120">
            <template #default="scope">
              ¥{{ (scope.row.outboundMoney || 0).toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="currentInventory" label="库存" width="100"></el-table-column>
          <el-table-column prop="position" label="库位" width="100"></el-table-column>
          <el-table-column prop="batchNumber" label="批次号" width="120"></el-table-column>
          <el-table-column prop="productionDate" label="生产日期" width="120">
            <template #default="scope">
              {{ formatDate(scope.row.productionDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip></el-table-column>
        </el-table>

        <!-- 暂无数据提示 -->
        <div v-if="!detailLoading && outboundDetails.length === 0" class="no-data">
          <el-empty description="暂无数据"></el-empty>
        </div>
      </el-card>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import axios from 'axios';

// 路由
const route = useRoute();
const router = useRouter();

// 获取路由参数
const outboundId = ref(route.params.id || route.query.id);
const outboundCode = ref(route.query.outboundCode || '');

// 数据
const loading = ref(false);
const detailLoading = ref(false);
const outboundInfo = reactive({});
const outboundDetails = ref([]);

// 防止重复请求
let isLoading = false;

// 初始化
onMounted(() => {
  if (outboundId.value) {
    loadOutboundDetail();
  } else {
    ElMessage.error('缺少出库单ID参数');
    goBack();
  }
});

// 监听路由参数变化
watch(() => route.params.id, (newId) => {
  if (newId && newId !== outboundId.value) {
    outboundId.value = newId;
    loadOutboundDetail();
  }
}, { immediate: false });

// 监听路由查询参数变化
watch(() => route.query.outboundCode, (newCode) => {
  if (newCode) {
    outboundCode.value = newCode;
  }
}, { immediate: false });

// 加载出库单详情
const loadOutboundDetail = async () => {
  // 防止重复请求
  if (isLoading) {
    console.log('正在加载中，跳过重复请求');
    return;
  }
  
  isLoading = true;
  loading.value = true;
  detailLoading.value = true;
  
  // 清空之前的数据
  outboundDetails.value = [];
  Object.keys(outboundInfo).forEach(key => {
    delete outboundInfo[key];
  });

  try {
    // 先获取出库明细信息
    const detailResponse = await axios.get(`/api/Outbound/GetOutboundDetails/GetOutboundDetails/${outboundId.value}`);
    
    console.log('出库明细API返回数据:', detailResponse.data);
    
    // 注意：我们主要依赖sessionStorage中的数据，不再调用可能出错的基础信息API
    console.log('优先使用sessionStorage中的数据获取基础信息');
    
    // 优先尝试从sessionStorage获取基础信息
    let baseData = null;
    try {
      const storedInfo = sessionStorage.getItem('currentOutboundInfo');
      if (storedInfo) {
        const parsedInfo = JSON.parse(storedInfo);
        if (parsedInfo && (parsedInfo.id == outboundId.value || parsedInfo.outboundId == outboundId.value)) {
          baseData = parsedInfo;
          console.log('从sessionStorage获取的基础信息:', baseData);
        }
      }
    } catch (e) {
      console.warn('解析sessionStorage数据失败:', e);
    }
    
    // 如果sessionStorage中没有数据，记录警告
    if (!baseData) {
      console.warn('sessionStorage中没有基础信息数据');
    }
    
    // 设置基础信息
    if (baseData) {
      outboundInfo.id = baseData.id;
      outboundInfo.outboundId = baseData.outboundId || baseData.id;
      outboundInfo.outboundCode = baseData.outboundCode || outboundCode.value;
      outboundInfo.inOutTypeName = baseData.inOutTypeName;
      outboundInfo.warehouseName = baseData.warehouseName;
      outboundInfo.outboundDate = baseData.outboundDate;
      outboundInfo.contact = baseData.contact;
      outboundInfo.consignee = baseData.consignee;
      outboundInfo.contactPhone = baseData.contactPhone;
      outboundInfo.userName = baseData.userName;
      outboundInfo.status = baseData.status;
      outboundInfo.outboundAllNum = baseData.outboundAllNum;
      outboundInfo.outboundAllMoney = baseData.outboundAllMoney;
      outboundInfo.outboundAllGoods = baseData.outboundAllGoods;
      outboundInfo.remark = baseData.remark;
      outboundInfo.creator = baseData.creator;
      outboundInfo.createDate = baseData.createDate;
      
      console.log('最终设置的基础信息:', outboundInfo);
    } else {
      console.warn('未找到出库单基础信息，尝试从明细中提取');
      
      // 如果基础信息获取失败，从明细中提取部分信息
      if (detailResponse.data && detailResponse.data.code === 200 && detailResponse.data.data && detailResponse.data.data.length > 0) {
        const firstDetail = detailResponse.data.data[0];
        outboundInfo.outboundCode = firstDetail.outboundCode || outboundCode.value;
        outboundInfo.status = firstDetail.status;
        outboundInfo.creator = firstDetail.creator;
        outboundInfo.createDate = firstDetail.createDate;
        outboundInfo.remark = firstDetail.remark;
        console.log('从明细中提取的基础信息:', outboundInfo);
      }
    }
    
    // 处理明细信息
    if (detailResponse.data && detailResponse.data.code === 200) {
      if (detailResponse.data.data && detailResponse.data.data.length > 0) {
        // 设置明细数据
        outboundDetails.value = detailResponse.data.data.map(item => ({
          ...item,
          unitPrice: item.unitPrice || 0,
          outboundNum: item.oneOutboundNum || 0,
          outboundMoney: (item.unitPrice || 0) * (item.oneOutboundNum || 0)
        }));

        console.log('处理后的明细数据:', outboundDetails.value);
        
        // 使用 nextTick 确保DOM更新
        await nextTick();
      } else {
        ElMessage.warning('未找到出库明细数据');
      }
    } else {
      ElMessage.error(detailResponse.data?.message || '获取出库明细失败');
    }
  } catch (error) {
    console.error('获取出库详情失败:', error);
    
    if (error.response) {
      console.error('响应错误:', error.response.status, error.response.data);
      ElMessage.error(`获取数据失败: ${error.response.status} ${error.response.statusText}`);
    } else if (error.request) {
      console.error('请求错误:', error.request);
      ElMessage.error('网络连接失败，请检查网络连接');
    } else {
      console.error('其他错误:', error.message);
      ElMessage.error(`获取数据失败: ${error.message}`);
    }
  } finally {
    loading.value = false;
    detailLoading.value = false;
    isLoading = false;
  }
};

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    return date.toISOString().split('T')[0];
  } catch (e) {
    return dateString;
  }
};

// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  try {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    });
  } catch (e) {
    return dateString;
  }
};

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '草稿';
    case 1: return '待审核';
    case 2: return '已审核';
    case 3: return '已出库';
    case 4: return '已取消';
    default: return '未知状态';
  }
};

// 获取状态对应的类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return ''; // 草稿
    case 1: return 'warning'; // 待审核
    case 2: return 'success'; // 已审核
    case 3: return 'success'; // 已出库
    case 4: return 'danger'; // 已取消
    default: return '';
  }
};

// 刷新数据
const refreshData = () => {
  console.log('手动刷新数据');
  // 清除sessionStorage，强制重新获取数据
  sessionStorage.removeItem('currentOutboundInfo');
  isLoading = false; // 重置加载状态
  loadOutboundDetail();
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};
</script>

<style scoped>
.outbound-detail-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.info-card, .detail-card {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.info-item label {
  font-weight: bold;
  color: #606266;
  min-width: 80px;
  margin-right: 10px;
}

.info-item span {
  color: #303133;
}

.no-data {
  text-align: center;
  padding: 40px 0;
}

.el-row {
  margin-bottom: 0;
}

.el-col {
  margin-bottom: 15px;
}
</style>
